# -*- coding: utf-8 -*-

"""
@Datetime: 2019/1/30
@Author: Zhang Yafei
"""
import base64
import json
import uuid
from flask import Blueprint, request, jsonify, make_response, redirect, g
import os
import traceback
from common.libs.helper import ops_render
from application import app, db
from common.models import models
from common.libs.UserService import UserService

route_user = Blueprint('user_page', __name__)


@route_user.route('/edit', methods=['GET', 'POST'])
def edit():
    """
    个人信息编辑
    :return:
    """
    if request.method == 'GET':
        return ops_render('user/edit.html')
    resp = {'code':200, 'msg':'操作成功', 'data':{}}
    req = request.values
    nickname = req['nickname'] if 'nickname' in req else ''
    email = req['email'] if 'email' in req else ''

    if nickname is None or len(nickname) < 1:
        resp['code'] = -1
        resp['msg'] = '请输入符合规范的姓名~~'
        return jsonify(resp)

    if email is None or len(email) < 1:
        resp['code'] = -1
        resp['msg'] = '请输入符合规范的邮箱~~'
        return jsonify(resp)

    user_info = g.current_user
    user_info.nickname = nickname
    user_info.email = email

    db.session.add(user_info)
    db.session.commit()

    return jsonify(resp)


@route_user.route('/reset-pwd', methods=['GET', 'POST'])
def resetPwd():
    """
    重置密码
    :return:
    """
    if request.method == 'GET':
        return ops_render('user/reset_pwd.html')

    resp = {'code':200, 'msg':'操作成功', 'data':{}}
    req = request.values
    old_password = req['old_password'] if 'old_password' in req else ''
    new_password = req['new_password'] if 'new_password' in req else ''

    if old_password is None or len(old_password) < 6:
        resp['code'] = -1
        resp['msg'] = '请输入符合规范的原密码'
        return jsonify(resp)

    if new_password is None or len(new_password) < 6:
        resp['code'] = -1
        resp['msg'] = '请输入符合规范的原密码'
        return jsonify(resp)

    if old_password == new_password:
        resp['code'] = -1
        resp['msg'] = '请重新输入一个吧，新密码和原密码不能相同'
        return jsonify(resp)

    user_info = g.current_user
    user_info.login_pwd = UserService.genePwd(new_password, user_info.login_salt)

    db.session.add(user_info)
    db.session.commit()

    response = make_response(json.dumps(resp))
    response.set_cookie(app.config['AUTH_COOKIE_NAME'], '%s#%s'%(UserService.genAuthCode(user_info), user_info.uid), 60 * 60 * 24 * 120)  # 保存120天
    return response


@route_user.route('/upload_avatar', methods=['GET','POST'])
def upload_avatar():
    """
    上传头像
    :return:
    """
    if request.method == 'GET':
        return ops_render('user/imagecrop.html')
    resp = {'code': 1000}
    try:
        user = g.current_user
        origin_img = "static" + user.avatar if user.avatar else ''
        img = request.values.get('img')
        img = img.split('base64,')[1]
        images = base64.b64decode(img)
        file_name = str(uuid.uuid1())
        with open('static/images/photo/{}.jpg'.format(file_name), 'wb') as f:
            f.write(images)
        avatar = os.path.join('/images/photo',file_name+'.jpg')
        user.avatar = avatar
        db.session.add(user)
        db.session.commit()
        if origin_img:
            os.remove(origin_img)
        resp['msg'] = '上传成功'
    except Exception as e:
        traceback.print_exc()
        resp['code'] = 1001
        resp['error'] = '上传失败'
    return jsonify(resp)